package cn.edu.zjicm.wordsnet_d.synchronize;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.content.Context;
import android.os.Handler;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import cn.edu.zjicm.wordsnet_d.pay.Alipay;
import cn.edu.zjicm.wordsnet_d.pay.Order;
import cn.edu.zjicm.wordsnet_d.pay.Product;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;

public class PayInterface extends ServerInterface {

	private static PayInterface mInstance;

	public static PayInterface getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new PayInterface(context);
		}
		return mInstance;
	}

	private PayInterface(Context context) {
		super(context);
	}

	/*------------------- 商品列表 ---------------*/
	public void getCommodityList(Handler handler) {
		LogUtil.d("调用getCommodityList()");
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new GetCommodityListThread(handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(PayInterface.MSG_BAD_NETWORK));
		}
		MobclickAgentData.register(context, "尝试注册");
	}

	public class GetCommodityListThread extends Thread {
		Handler handler;

		GetCommodityListThread(Handler handler) {
			this.handler = handler;
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			try {
				HttpPost post = new HttpPost(GET_COMMODITY_LIST);
				HttpResponse response = client.execute(post);

				int code = response.getStatusLine().getStatusCode();
				LogUtil.d("code="+code);
				
				if (code== 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					LogUtil.d(str);
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");
					if (success) {
						String data = result.getString("list");
						Gson gson = new Gson();
						List<Product> productList = gson.fromJson(data, new TypeToken<List<Product>>() {
						}.getType());
						WordFactory.getInstance(context).importProductList(productList);
						handler.sendMessage(handler.obtainMessage(PayInterface.MSG_SUCCESS));
					} else {
						handler.sendMessage(handler.obtainMessage(PayInterface.MSG_REGISTERED));
					}
					// String str1 = message + "\n" + success + "\n" + token;
					// Toast.makeText(context, str1, Toast.LENGTH_SHORT).show();
				} else {
					handler.sendMessage(handler.obtainMessage(PayInterface.MSG_WEB_SITE_ERROR));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(PayInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

	/*------------------- 用户财富值zmd ---------------*/
	public void getUserWealth() {
		Handler handler = new GetUserWealthHandler();
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new GetUserWealthThread(handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
		// MobclickAgentData.changeNickName(context);
	}

	public void getUserWealth(Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new GetUserWealthThread(handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
		// MobclickAgentData.changeNickName(context);
	}

	public class GetUserWealthThread extends Thread {
		String token;
		Handler handler;

		GetUserWealthThread(Handler handler) {
			this.token = AppPreference.getToken(context);
			this.handler = handler;
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			list.add(pair1);
			try {
				HttpEntity entity = new UrlEncodedFormEntity(list, "utf-8");
				HttpPost post = new HttpPost(GET_USER_WEALTH);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");
					if (success) {
						int zmd = result.getInt("zmd");
						WordFactory.getInstance(context).setZMD(zmd);
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS));
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

	class GetUserWealthHandler extends Handler {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case UserInterface.MSG_START:
				break;
			case UserInterface.MSG_SUCCESS:
				LogUtil.e("获取财富值 成功");
				break;
			case UserInterface.MSG_UNSUCCESS:
				LogUtil.e("获取财富值 失败");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				LogUtil.e("获取财富值 失败");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				LogUtil.e("获取财富值 失败");
				break;
			default:
				break;
			}
		};
	};

	/*------------------- 用户已购买商品信息 ---------------*/
	public void getUserBought() {
		Handler handler = new GetUserBoughtHandler();
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new GetUserBoughtThread(handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
		// MobclickAgentData.changeNickName(context);
	}

	public void getUserBought(Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new GetUserBoughtThread(handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
		// MobclickAgentData.changeNickName(context);
	}

	public class GetUserBoughtThread extends Thread {
		String token;
		Handler handler;

		GetUserBoughtThread(Handler handler) {
			this.token = AppPreference.getToken(context);
			this.handler = handler;
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			list.add(pair1);
			try {
				HttpEntity entity = new UrlEncodedFormEntity(list, "utf-8");
				HttpPost post = new HttpPost(GET_USER_BOUGHT);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");
					if (success) {
						String data = result.getString("bought");
						Gson gson = new Gson();
						List<Order> orderList = gson.fromJson(data, new TypeToken<List<Order>>() {
						}.getType());
						WordFactory.getInstance(context).importOrderList(orderList);
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS));
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

	class GetUserBoughtHandler extends Handler {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case UserInterface.MSG_START:
				break;
			case UserInterface.MSG_SUCCESS:
				LogUtil.e("获取已购买产品信息 成功");
				break;
			case UserInterface.MSG_UNSUCCESS:
				LogUtil.e("获取已购买产品信息 失败");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				LogUtil.e("获取已购买产品信息 失败");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				LogUtil.e("获取已购买产品信息 失败");
				break;
			default:
				break;
			}
		};
	};

	/*------------------- zmd购买商品(单词书) ---------------*/
	public void buyWithZmd(String product, Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new BuyWithZmdThread(product, handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
		// MobclickAgentData.changeNickName(context);
	}

	public class BuyWithZmdThread extends Thread {
		String token;
		String product;
		Handler handler;

		BuyWithZmdThread(String product, Handler handler) {
			this.token = AppPreference.getToken(context);
			this.product = product;
			this.handler = handler;
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			NameValuePair pair2 = new BasicNameValuePair("product", product);
			list.add(pair1);
			list.add(pair2);
			try {
				HttpEntity entity = new UrlEncodedFormEntity(list, "utf-8");
				HttpPost post = new HttpPost(BUY_WITH_ZMD);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");
					if (success) {
						String data = result.getString("bought");
						Gson gson = new Gson();
						List<Order> orderList = gson.fromJson(data, new TypeToken<List<Order>>() {
						}.getType());
						WordFactory.getInstance(context).importOrderList(orderList);
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS));
					} else {
						LogUtil.e("购买失败" + message);
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

	/*------------------- createAlipayOrder.htm ---------------*/
	public void createAlipayOrder(String product, Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new CreateAlipayOrderThread(product, handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
		// MobclickAgentData.changeNickName(context);
	}

	public class CreateAlipayOrderThread extends Thread {
		String token;
		String product;
		Handler handler;

		CreateAlipayOrderThread(String product, Handler handler) {
			this.token = AppPreference.getToken(context);
			this.product = product;
			this.handler = handler;
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			NameValuePair pair2 = new BasicNameValuePair("product", product);
			list.add(pair1);
			list.add(pair2);
			try {
				HttpEntity entity = new UrlEncodedFormEntity(list, "utf-8");
				HttpPost post = new HttpPost(CREATE_ALIPAY_ORDER);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");
					if (success) {
						String data = result.getString("order");
						Gson gson = new Gson();
						Order order = (Order) gson.fromJson(data, Order.class);
						JSONObject result1 = new JSONObject(data);
						order.setOrderId(result1.getLong("id"));
						order.setUserId(result1.getInt("buyerId"));
						WordFactory.getInstance(context).insertOrderLog(order);
						Alipay.currentOrder = order;
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS, order.getOrderId() + ""));
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

}
